import React, { Component } from 'react';
import { Tree,Button} from "antd";
import {
    EditOutlined,
    PlusOutlined,
    MinusOutlined,
} from "@ant-design/icons";
const { TreeNode } = Tree;
export default class Index extends Component {
    constructor(props) {
        super(props);
        this.state = {
            treeData: [
                {
                    value: "0",
                    key: "0",
                    children: [
                        {
                            value: "0-1",
                            key: "0-1",
                        },
                        {
                            value: "0-2",
                            key: "0-2",
                        },
                    ],
                },
            ]
        }
    }
    renderTreeNodes = (data) => {
        //console.log(data)
        let nodeArr = data.map((item) => {
            item.title = (
                <div>
                    <Button type='primary' style={{display:'block'}}>新增角色</Button>
                    <span>{item.value}</span>
                    <span>
                        <EditOutlined style={{ marginLeft: 10, color: 'blue' }} />

                        <PlusOutlined style={{ marginLeft: 10 }} onClick={() => this.onAdd(item.key)} />

                        <MinusOutlined style={{ marginLeft: 10 }} />
                    </span>
                </div>
            );
            if (item.children) {
                return (
                    <TreeNode title={item.title} key={item.key} dataRef={item}>
                        {this.renderTreeNodes(item.children)}
                    </TreeNode>
                );
            }

            return <TreeNode title={item.title} key={item.key} />;
        });

        return nodeArr;
    };
    onAdd = (key) => {
       
        this.addNode(key, this.state.treeData);
        //useState里数据务必为immutable （不可赋值的对象），所以必须加上slice()返回一个新的数组对象
        //this.setState({})
    };
    addNode = (key, data) =>
        data.forEach((item) => {
            //console.log(key,data,item.key)
            if (item.key === key) {
                console.log(item,this.state.treeData)
                if (item.children) {
                    item.children.push({
                        value: "default",
                        key: key + Math.random(100), // 这个 key 应该是唯一的
                    });
                } else {
                    item.children = [];
                    item.children.push({
                        value: "default",
                        key: key + Math.random(100),
                    });
                }
                return;
            }
            if (item.children) {
                this.addNode(key, item.children);
            }
            console.log(data)
        });
    render() {
        return (
            <div>
                <Tree>{this.renderTreeNodes(this.state.treeData)}</Tree>
            </div>
        );
    }
}